# Definition for a binary tree node.

from typing import Optional, List


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]:
        vals = []

        def dfs(node: Optional[TreeNode]):
            nonlocal vals
            if node is None:
                return
            if node.left:
                dfs(node.left)
            vals.append(node.val)
            if node.right:
                dfs(node.right)
            return

        dfs(root)
        return [self.binary_search_eq(vals, target) for target in queries]

    def binary_search_eq(self, vals: List[int], target):
        left = -1
        right = len(vals)
        while left + 1 < right:
            mid = (left + right) // 2
            if vals[mid] == target:
                return [target, target]
            elif vals[mid] > target:
                right = mid
            else:
                left = mid
        ret = [vals[left] if left >= 0 else -1, vals[right] if right < len(vals) else -1]
        return ret
